
#include <QQuickOpenGLUtils> 
#include <QOpenGLContext>
#include <QOpenGLFunctions>

#include <osgViewer/GraphicsWindow>

#include "OsgQuickView.h"
#include "OsgQuickWindow.h"

namespace OsgQtQuick
{
    std::map<QQuickWindow*, OsgQuickWindow*> OsgQuickWindow::s_mapWindows = 
        std::map<QQuickWindow*, OsgQuickWindow*>();

    OsgQuickWindow::OsgQuickWindow(QQuickWindow* window)
        : QObject(window)
        , m_pWindow(window)
    {
        m_ptrOsgGraphicsContext = new osgViewer::GraphicsWindowEmbedded(
            0,
            0,
            window->width() * window->devicePixelRatio(),
            window->height() * window->devicePixelRatio());

        m_ptrCompositeViewer = new osgViewer::CompositeViewer;
        m_ptrCompositeViewer->setThreadingModel(osgViewer::ViewerBase::SingleThreaded);
        m_ptrCompositeViewer->setKeyEventSetsDone(0);

        //auto resizeWindow = [&]() {this->m_ptrOsgGraphicsContext->resizedImplementation(
        //    this->m_pWindow->x() * window->devicePixelRatio(),
        //    this->m_pWindow->x() * window->devicePixelRatio(),
        //    this->m_pWindow->width() * window->devicePixelRatio(),
        //    this->m_pWindow->height() * window->devicePixelRatio()); };
        //connect(m_pWindow, &QQuickWindow::widthChanged, resizeWindow);
        //connect(m_pWindow, &QQuickWindow::heightChanged, resizeWindow);

        //connect(m_pWindow, &QQuickWindow::beforeRendering, this, &OsgQuickWindow::frame, Qt::DirectConnection);
        connect(m_pWindow, &QQuickWindow::beforeRenderPassRecording, this, &OsgQuickWindow::frame, Qt::DirectConnection);

        m_iUpdateTimer = startTimer(20);
    }

    OsgQuickWindow* OsgQuickWindow::fromWindow(QQuickWindow* window)
    {
        if (!window) return 0;

        auto it =
            OsgQuickWindow::s_mapWindows.find(window);

        if (it != OsgQuickWindow::s_mapWindows.end()) return it->second;

        return new OsgQuickWindow(window);
    }

    void OsgQuickWindow::frame()
    {
        if (!m_pWindow) return;

        m_pWindow->beginExternalCommands();

        QQuickOpenGLUtils::resetOpenGLState();
        m_ptrCompositeViewer->frame();

        m_pWindow->endExternalCommands();

    }

    void OsgQuickWindow::addView(OsgQuickView* view)
    {
        if(view && view->getView())
            m_ptrCompositeViewer->addView(view->getView());
    }

    void OsgQuickWindow::sync()
    {
        
    }

    void OsgQuickWindow::cleanup()
    {
       
    }

    void OsgQuickWindow::timerEvent(QTimerEvent* event)
    {
        if (!m_pWindow) return;

        if (event->timerId() == m_iUpdateTimer)
        {
            m_pWindow->update();
        }
    }
}
